/*
 *  (C) Copyright 2008 Insula T.I. Ltda.
 * 
 *  This file is part of Vulcano.
 *
 *  Vulcano is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Vulcano is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with Vulcano.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.openinsula.vulcano.orm.dao.hibernate;

import java.util.LinkedList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;
import org.hibernate.Session;
import org.openinsula.vulcano.orm.dao.Dao;
import org.openinsula.vulcano.orm.dao.query.DaoQuery;
import org.openinsula.vulcano.orm.dao.query.spec.Spec;

/**
 * @author rebola
 * @author yanaga
 * @since 1.1
 * @see Dao
 * @see DaoQuery
 * @see HibernateDao
 */
public class HibernateQuerySupport {
	protected final Log logger = LogFactory.getLog(getClass());

	@SuppressWarnings("unchecked")
	public List executeQuery(final Session session, final DaoQuery daoQuery) {
		Query query = session.createQuery(createHql(daoQuery));
		configureQuery(query, daoQuery);

		return query.list();
	}

	protected String createHql(final DaoQuery<?> daoQuery) {
		StringBuilder sb = new StringBuilder();

		sb.append(daoQuery.accept(new FromHqlDaoQueryVisitor()));

		Spec abstractSpec = daoQuery.getSpec();

		if (abstractSpec != null) {
			sb.append(abstractSpec.accept(new HqlSpecVisitor()));
		}

		sb.append(daoQuery.accept(new OrderHqlDaoQueryVisitor()));

		if (logger.isDebugEnabled()) {
			logger.debug("Translated HQL: " + sb.toString());
		}

		return sb.toString();
	}

	protected void configureQuery(final Query query, final DaoQuery<?> daoQuery) {
		List<Object> params = new LinkedList<Object>();
		Spec spec = daoQuery.getSpec();

		if (spec != null) {
			params = spec.accept(new ParameterSpecVisitor());
		}

		int i = 0;
		for (Object value : params) {
			if (value != null) {
				query.setParameter(i++, value);

				if (logger.isDebugEnabled()) {
					logger.debug(String.format("[%d] = %s", i, value));
				}
			}
		}

		daoQuery.accept(new IntervalDaoQueryVisitor(query));
		daoQuery.accept(new LockDaoQueryVisitor(query));
	}

}
